package com.ycl.productservice.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycl.productservice.entity.PageVO;
import com.ycl.productservice.entity.Product;
import com.ycl.productservice.service.ProductService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ProductController {

    @Resource
    private ProductService productService;

    @SentinelResource(value = "product/{id}",
            blockHandler = "findProductByIdBlockHandler",
            blockHandlerClass = MyBlockHandler.class)
    @GetMapping("/product/{id}")
    public ResponseEntity<Product> findProductById(@PathVariable Integer id) {
        Product product = productService.getById(id);
        if (product == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(product);
    }

    @GetMapping("/products")
    public ResponseEntity<List<Product>> findAllProducts(){
        List<Product> list = productService.list();
        return ResponseEntity.ok(list);
    }

    @GetMapping("/products-page")
    public ResponseEntity<PageVO> findProductsPage(
            @RequestParam(value = "current",required = false,defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize){
        Page<Product> page = productService.page(new Page<>(current, pageSize));
        PageVO pageVO = new PageVO(current,pageSize,page.getTotal(),page.getRecords());
        return ResponseEntity.ok(pageVO);
    }

    @PostMapping("/product")
    public ResponseEntity<String> addProduct(@RequestBody Product product){
        productService.save(product);
        return ResponseEntity.ok("OK");
    }

    @PutMapping("/product")
    public ResponseEntity<String> updateProduct(@RequestBody Product product){
        productService.updateById(product);
        return ResponseEntity.ok("OK");
    }

    @DeleteMapping("/product/{id}")
    public ResponseEntity<String> deleteProduct(@PathVariable Integer id){
        productService.removeById(id);
        return ResponseEntity.ok("OK");
    }
}